package sr.codemg.service.impl;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import sr.codemg.config.JwtConfig;
import sr.codemg.config.RedisUtil;
import sr.codemg.entity.SysUsers;
import sr.codemg.service.LoginService;
import sr.codemg.service.SysUsersService;
import sr.codemg.utils.Constants;
import sr.codemg.utils.ResponseCode;
import sr.codemg.utils.TokenManager;
import sr.codemg.vm.Base;
import sr.codemg.vm.Login;
import sr.codemg.vm.Passwd;

import javax.servlet.http.HttpServletResponse;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    SysUsersService sysUsersService;
    @Autowired
    RedisUtil redisUtil;

    @Override
    public Base.Response login(Login.Request entity, HttpServletResponse response) {
        SysUsers user = sysUsersService.get(entity.getUserId());
        if (user == null) {
            return ResponseCode.getBase("00002");
        } else {
            entity.setUserId(user.getAccount());
        }
        if (!user.getPass().equals(entity.getPasswd())) {
            return ResponseCode.getBase("00003");
        }

        deleteUserCache(user.getAccount(), null);
        String token = JwtConfig.create(entity, user.getRoleId());
        TokenManager.setCookie(response, Constants.Authorization, token);

        redisUtil.hset(entity.getUserId(), Constants.USER_CONFIG.JWT_TOKENS, token);
        redisUtil.set(token, entity.getUserId());

        redisUtil.expire(user.getAccount(), Constants.USER_CONFIG.CACHE_TIMEOUT);
        redisUtil.expire(token, Constants.USER_CONFIG.CACHE_TIMEOUT);

        Login.Response result = new Login.Response(Constants.SUCC, "认证成功", token);

        result.setUserId(entity.getUserId());
        result.setUserName(user.getName());
        return result;
    }

    @Override
    public Base.Response updatePass(Passwd.Request entity) {
        SysUsers user = sysUsersService.get(entity.getUserId());
        if (user == null) {
            return ResponseCode.getBase("00002");
        }
        if (!user.getPass().equals(entity.getPasswd())) {
            return ResponseCode.getBase("00003");
        }
        user.setPass(entity.getNewPasswd());
        sysUsersService.update(user);
        return ResponseCode.getBase(Constants.SUCC);
    }

    @Override
    public void deleteUserCache(String userId, String token) {
        if (!StringUtils.isEmpty(userId)) redisUtil.del(userId);
        if (!StringUtils.isEmpty(token)) redisUtil.del(token);
    }

}
